<template>
  <div class="amend">
    <!-- 顶部 -->
    <van-nav-bar
      title="修改头像"
      left-arrow
      right-text="保存"
      @click-right="onClickRight"
    >
      <template #left>
        <i class="iconfont  icon-zuojiantou" @click="$router.back()"></i
      ></template>
    </van-nav-bar>
    <!-- 图片 -->
    <van-uploader
      v-if="sum === 2"
      :max-size="2024 * 1024"
      @oversize="onOversize"
      class="amend_head"
      v-model="fileList"
      :max-count="1"
      preview-size="200px"
      :after-read="afterRead"
    />
  </div>
</template>

<script>
import { Headportrait, setUserinfo } from '@/api/mine.js'
import { mapState } from 'vuex'
export default {
  name: 'amend',
  data () {
    return {
      fileList: [],
      id: '',
      sum: 2
    }
  },
  methods: {
    async afterRead (file) {
      // console.log(file)
      let fd = new FormData()
      fd.append('files', file.file)
      const res = await Headportrait(fd)
      // console.log(res)
      this.id = res.data.data[0].id
      // 保存vuex
      this.$store.commit('setUserlist', {
        ...this.Userlist,
        avatar: res.data.data[0].url
      })
    },
    // 保存
    async onClickRight () {
      await setUserinfo({ avatar: this.id })
      this.$toast.loading({
        message: '更新中...',
        forbidClick: true,
        duration: 500
      })
      this.$router.push('/compile')
    },
    onOversize (file) {
      // console.log(file)
      this.$toast({
        message: '图片大小不能超过 2m',
        forbidClick: true,
        duration: 500
      })
    }
  },
  computed: {
    ...mapState(['Userlist'])
  },
  created () {
    // this.fileList = [{ url: `http://localhost:1337${Userlist.avatar}` }]
    this.fileList.push({ url: `http://localhost:1337${this.Userlist.avatar}` })
  }
}
</script>

<style lang="less">
* {
  margin: 0;
  padding: 0;
}
body {
  background-color: #f7f4f5;
}
.amend {
  // 顶部
  .van-nav-bar__title {
    font-weight: 700;
    font-size: 18.8px;
  }
  span.van-nav-bar__text {
    color: #000;
  }
  i.iconfont.icon-zuojiantou {
    margin-left: -8px;
    font-size: 24px;
  }
  //   头像
  .amend_head {
    margin-top: 10px;
    margin-left: 50%;
    transform: translate(-50%);
  }
}
</style>
